package hu.issue.ejb;

import hu.issue.entity.Task;
import hu.issue.entity.TaskState;
import hu.issue.entity.User;
import hu.issue.exceptions.TaskNotFoundException;
import hu.issue.exceptions.UserNotFoundException;
import hu.issue.framework.security.SecurityContext;

import java.util.Date;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

@Stateless
public class TaskServiceBean implements TaskService {
	@PersistenceContext
	private EntityManager manager;

	@EJB
	private UserService userService;

	@Override
	public void createTask(final Task task) {
		this.manager.persist(task);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Task> getInactiveTasks() {
		final Query query = this.manager.createQuery("select t from Task t where t.milestone is null");
		return query.getResultList();
	}

	@Override
	public Task findTaskById(final int taskId) throws TaskNotFoundException {
		final Task task = this.manager.find(Task.class, taskId);
		if (task == null) {
			throw new TaskNotFoundException();
		}
		return task;
	}

	@Override
	public void assignTaskToMySelf(final int taskId) throws TaskNotFoundException {
		final Task task = findTaskById(taskId);
		if (task.getState() != TaskState.NEW) {
			throw new IllegalStateException();
		}
		final User currentUser = this.manager.merge(SecurityContext.getCurrentUser());

		task.setAssignee(currentUser);
	}

	@Override
	public void closeTask(final int taskId) throws TaskNotFoundException {
		final Task task = findTaskById(taskId);
		if (task.getState() != TaskState.ASSIGNED) {
			throw new IllegalStateException();
		}

		final User currentUser = this.manager.merge(SecurityContext.getCurrentUser());

		if (!task.getAssignee().getUserName().equals(currentUser.getUserName())) {
			throw new IllegalStateException();
		}

		task.setResolvedDate(new Date());
	}

	@Override
	public void assignTo(final int taskId, final String userName) throws TaskNotFoundException, UserNotFoundException {
		final Task task = findTaskById(taskId);
		if (task.getState() != TaskState.NEW) {
			throw new IllegalStateException();
		}

		final User user = this.userService.findUserByUserName(userName);
		task.setAssignee(user);
	}
}